<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request){
       /* $this->validate($request,[
            'email' => 'required|email',
            'password' => 'required',
                'is_remember' => 'integer'
        ]);*/

        if($this->attemptLogin($request)){
            $user = $this->guard('api')->user();
            $user->api_token = str_random(64);
            $user->save();
            return response()->json(['data'=>$user->toArray()]);
        }
        return response()->json(['data'=>'Username or Password error'],404);
    }


    public function logout(Request $request)
    {
        $api_token = $request->input('api_token');
        $user = User::where('api_token',$api_token)->first();
        if($user){
            $user->api_token = '';
            $user->save();
            return response()->json(['data'=>'退出成功！']);
        }
    }

}
